package com.kuang.controller;


import com.kuang.common.exception.KuangShenException;
import com.kuang.common.generator.redis.GeneratorIdServiceImpl;
import com.kuang.entity.Order;
import com.kuang.service.order.OrderServiceImpl;
import com.kuang.utils.SnowflakeIdWorker;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * @author 飞哥yykk
 * 更多学习关注飞哥B站
 * 地址是：https://space.bilibili.com/490711252
 * @title: OrderController
 * @projectName tinyid
 * @description: TODO
 * @date 2021/9/320:43
 */
@RestController
public class OrderController {

    private final static Logger log = LoggerFactory.getLogger(OrderController.class);

    @Value("${server.port}")
    private String ports;

    @Autowired
    private OrderServiceImpl orderService;

    @Autowired
    private GeneratorIdServiceImpl generatorIdService;


//    @Autowired
//    private WxMaService wxMaService;
//
//    @Autowired
//    private UserService userService;


    @GetMapping("/getPorts")
    public  String getPorts(){
        return ports;
    }

//    @Autowired
//    private IGeneratorIdService generatorIdService;

    @Autowired
    private CuratorFramework client;

//     单节点的多并发请求，用synchronized 锁升级---阻塞 jvm 或者lock锁
//     token 可以解决什么？token可以允许你重复再次购买
//     下单----一个用户在30s之内不论执行多少次下单，其结论都是一样的， 200 1 199
    @GetMapping("/saveorder")
    public Order makeOrder(Order order) {
        InterProcessMutex lock = new InterProcessMutex(client, "/order/" + order.getUserId() + "/" + order.getProductId());
        try {
            // 作业：求证lock的30秒之后会自动删除吗？
            boolean acquire = lock.acquire(5, TimeUnit.SECONDS); // 5~30s
            log.info("acquire============>{}", acquire);
            if (acquire) {
                log.info("{}------>拿到锁了......", Thread.currentThread().getName());
                // 订单号
                String orderNumber = new SnowflakeIdWorker(1, 1).nextId() + "";
                // 业务号
                String bitOrderNumber = generatorIdService.getSequence("ksd_make_order");
                order.setUserId(order.getUserId());
                order.setProductId(order.getProductId());
                order.setOrderNumber(orderNumber);
                order.setBitNumber(bitOrderNumber);
                order.setAvatar("a.jpg");
                order.setIp("127.0.0.1");
                order.setIpaddr("本机");
                order.setPaymethod(1);
                order.setPlatform(1);
                order.setUsername("yykk");
                order.setProductTitle("小米手机");
                order.setProductImg("xiaomi.jpg");
                order.setProductDesc("太贵了....");
                order.setProductPrice(new BigDecimal("1258.23"));
              orderService.saveOrder(order);
                log.info("下单成功:{}", order);
                return order;
            }
        } catch (Exception ex) {
            throw new KuangShenException(302, "你慢一点点");
        } finally {
            // 不能删除 临时
        }
        return null;
    }


    // 单节点的多并发请求，用synchronized 锁升级---阻塞 jvm 或者lock锁
 /*   @GetMapping("/saveorder")
    public Order makeOrder(Order order) {
        // 创建一个curator的分布式锁的对象InterProcessMutex
        InterProcessMutex lock = new InterProcessMutex(client, "/order/" + order.getUserId() + "/" + order.getProductId());
        try {
            // 作业：求证lock的30秒之后会自动删除吗？
            boolean acquire = lock.acquire(5, TimeUnit.SECONDS); // 5~30s
            log.info("acquire============>{}", acquire);
            if (acquire) {
                log.info("{}------>拿到锁了......", Thread.currentThread().getName());
                // 订单号
                String orderNumber = new SnowflakeIdWorker(1, 1).nextId() + "";
                // 业务号
                String bitOrderNumber = generatorIdService.getSequence("ksd_make_order");
                order.setUserId(order.getUserId());
                order.setProductId(order.getProductId());
                order.setOrderNumber(orderNumber);
                order.setBitNumber(bitOrderNumber);
                order.setAvatar("a.jpg");
                order.setIp("127.0.0.1");
                order.setIpaddr("本机");
                order.setPaymethod(1);
                order.setPlatform(1);
                order.setUsername("yykk");
                order.setProductTitle("小米手机");
                order.setProductImg("xiaomi.jpg");
                order.setProductDesc("太贵了....");
                order.setProductPrice(new BigDecimal("1258.23"));
                order = orderService.saveOrder(order);
                log.info("下单成功:{}", order);
                return order;
            }
        } catch (Exception ex) {
            throw new ValidationException(302, "你慢一点点");
        } finally {
//            // 不能删除 临时
        }
        return null;
    }*/


    //private Lock lock = new ReentrantLock();
    // 单节点的多并发请求，用synchronized 锁升级---阻塞 jvm 或者lock锁
//    @GetMapping("/saveorder")
//    public synchronized Order makeOrder(Order order) {
////        try {
////            boolean flag = lock.tryLock(3, TimeUnit.SECONDS);
////            if (flag) {
//              try {
//                log.info("获取到锁了......");
//                int countBuy = orderService.countUserMakeOrder(order.getUserId(), order.getProductId());
//                if (countBuy > 0) {
//                    throw new KuangShenException(205, "此商品已经购买了!!!");
//                }
//                // 订单号
//                String orderNumber = new SnowflakeIdWorker(1, 1).nextId() + "";
//                // 业务号
//                String bitOrderNumber = generatorIdService.getSequence("ksd_make_order");
//                order.setUserId(order.getUserId());
//                order.setProductId(order.getProductId());
//                order.setOrderNumber(orderNumber);
//                order.setBitNumber(bitOrderNumber);
//                order.setAvatar("a.jpg");
//                order.setIp("127.0.0.1");
//                order.setIpaddr("本机");
//                order.setPaymethod(1);
//                order.setPlatform(1);
//                order.setUsername("yykk");
//                order.setProductTitle("小米手机");
//                order.setProductImg("xiaomi.jpg");
//                order.setProductDesc("太贵了....");
//                order.setProductPrice(new BigDecimal("1258.23"));
//                orderService.saveOrder(order);
//                log.info("下单成功:{}", order);
//                return order;
//        } catch (Exception ex){
//            log.info("{} 2:当前线程：3秒都没有拿到锁，释放了....",Thread.currentThread().getName());
//            ex.printStackTrace();
//        }finally {
//            log.info("{}3: 释放到锁了......",Thread.currentThread().getName());
//         //   lock.unlock();
//        }
//
//        return null;
//    }

}
